package org.home.sys.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.home.base.validate.Add;
import org.home.sys.bean.SysUser;
import org.home.sys.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by awei on 2017/7/29.
 */
@Controller
@RequestMapping("/")
public class LoginController {
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("")
    public String toIndex() {
        return "index";
    }


    @RequestMapping("captcha/register")
    public String register(HttpServletRequest request, HttpServletResponse response, SysUser sysUser) {
        if (sysUser.getUserName() == null) {
            sysUser.setUserName(sysUser.getLoginName());
        }
        sysUserService.saveEntity(sysUser);
        return "index";
    }

    @RequestMapping("captcha/login")
    @RequiresUser()
    public String login(HttpServletRequest request, HttpServletResponse response, @Validated({Add.class}) SysUser sysUser, BindingResult validateResult) {
        boolean loginResult = false;
        if(!validateResult.hasErrors()){
            loginResult = shiroLogin(sysUser);
            System.out.println("no error");
        }else{
            validateResult.getAllErrors().forEach(a -> {
                System.out.println(a.getDefaultMessage());
            });
        }
        try {
            if (loginResult) {
                request.getSession().setAttribute("userName", sysUser.getLoginName());
                response.sendRedirect("/");
                return "index";
            } else {

                request.setAttribute("loginErrorMsg", "用户名或者密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("captcha/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response, SysUser sysUser) {

    }

    private boolean shiroLogin(SysUser sysUser) {
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), sysUser.getPassword());
        try {
            SecurityUtils.getSubject().login(token);
            return true;
        } catch (AuthenticationException e) {
            return false;
        }
    }

}
